package com.ruoyi.web.controller.sz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.sz.SzTimeLine;
import com.ruoyi.system.service.sz.ISzTimeLineService;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 时间轴Controller
 * 
 * @author ruoyi
 * @date 2024-03-16
 */
@Anonymous
@RestController
@RequestMapping("/sz/line")
public class SzTimeLineController extends BaseController
{
    @Autowired
    private ISzTimeLineService szTimeLineService;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询时间轴列表
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:list')")
    @GetMapping("/list")
    public TableDataInfo list(SzTimeLine szTimeLine)
    {
        startPage();
        List<SzTimeLine> list = szTimeLineService.selectSzTimeLineList(szTimeLine);
        return getDataTable(list);
    }

    /**
     * 导出时间轴列表
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:export')")
//    @Log(title = "时间轴", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SzTimeLine szTimeLine)
    {
        List<SzTimeLine> list = szTimeLineService.selectSzTimeLineList(szTimeLine);
        ExcelUtil<SzTimeLine> util = new ExcelUtil<SzTimeLine>(SzTimeLine.class);
        util.exportExcel(response, list, "时间轴数据");
    }

    /**
     * 获取时间轴详细信息
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:query')")
    @GetMapping(value = "/{timeId}")
    public AjaxResult getInfo(@PathVariable("timeId") Long timeId)
    {
        return success(szTimeLineService.selectSzTimeLineByTimeId(timeId));
    }

    /**
     * 新增时间轴
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:add')")
//    @Log(title = "时间轴", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SzTimeLine szTimeLine)
    {
        return toAjax(szTimeLineService.insertSzTimeLine(szTimeLine));
    }

    /**
     * 修改时间轴
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:edit')")
//    @Log(title = "时间轴", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SzTimeLine szTimeLine)
    {
        return toAjax(szTimeLineService.updateSzTimeLine(szTimeLine));
    }

    /**
     * 删除时间轴
     */
//    @PreAuthorize("@ss.hasPermi('sz:line:remove')")
//    @Log(title = "时间轴", businessType = BusinessType.DELETE)
	@DeleteMapping("/{timeIds}")
    public AjaxResult remove(@PathVariable Long[] timeIds)
    {
        return toAjax(szTimeLineService.deleteSzTimeLineByTimeIds(timeIds));
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getTimeLinePath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     *
     * @param year 所选年份
     */
    @GetMapping("/download")
    public void fileDownload(String year,  HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            String sourceFolderPath = RuoYiConfig.getTimeLinePath() + File.separator + year;
            String realFileName = year+".zip";
            String zipFilePath = RuoYiConfig.getTimeLinePath() + File.separator + realFileName;

            FileOutputStream fos = null;
            ZipOutputStream zos = null;
            try {
                fos = new FileOutputStream(zipFilePath);
                zos = new ZipOutputStream(fos);
                FileUtils.zipFolder(sourceFolderPath, sourceFolderPath, zos);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                zos.close();
                fos.close();
            }
//            System.out.println("文件夹压缩完成");

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(zipFilePath, response.getOutputStream());

        }
        catch (Exception e)
        {

        }
    }


    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
//            String localPath = RuoYiConfig.getTimeLinePath();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {

        }

    }
}
